<?php
/**
 * Created by PhpStorm.
 * User: yhg97p
 * Date: 2016/6/28
 * Time: 17:11
 */
session_start();
include __DIR__ . '/vendor/autoload.php';

use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;

$options = [
    'debug' => true,
    'app_id' => 'wx1cd5b8a5438c2130',
    'secret' => 'd65240fc907d1aad8d3386ea60d2726e ',
    'token' => 'w0Q52Arls2S9T2qlsRA215q09q2L9R2z',
    'aes_key' => 'Veg9MEUnmztEYnsJgniStH3ifk8O0RmlBQKzvUuwHXE',

    'log' => [
        'level' => 'debug',
        'file' => __DIR__ . '/log/' . date('Y-m-d') . '.log',
    ],
    'guzzle' => [
        'timeout' => 3.0, // 超时时间（秒）
        'verify' => false,
    ],
    'oauth' => [
        'scopes'   => ['snsapi_base'],  //snsapi_base | snsapi_userinfo
        'callback' => 'http://www.zbj1992.com/wx/oauth_callback.php',    //回调地址
    ],

    'payment' => [
        'merchant_id'        => '1386653202',
        'key'                => '3599d7bf0013d6a272b4d6d84c167296',
        'cert_path'          => __DIR__ . '/cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
        'key_path'           => __DIR__ . '/cert/apiclient_key.pem',      // XXX: 绝对路径！！！！
        'notify_url'         => 'http://www.zbj1992.com/wx/payback.php',       // 你也可以在下单时单独设置来想覆盖它
    ],
];

$app = new Application($options);

$oauth = $app->oauth;

//判断是否登录
if (empty($_SESSION['wechat_user'])) {
    $response = $oauth->redirect();
    return $response->send();
}
$order_no = $_GET['order_no'];
$total_fee = $_GET['total_fee'];
$payment = $app->payment;
$attributes = [
    'openid' => $_SESSION['wechat_user']['id'],
    'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
    'body'             => '水果团购支付订单',
    'detail'           => '水果团购支付订单',
    'out_trade_no'     => $order_no,
    'total_fee'        => $total_fee,
];

$order = new Order($attributes);

$result = $payment->prepare($order);
$prepayId = '';
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
    $prepayId = $result->prepay_id;
}
//微信统一下单最好和调起支付在不同页面,没刷新一次就会在微信生成一个预支付订单
if( $prepayId ){
    $json = $payment->configForPayment($prepayId);
}
echo $json;
?>
